package com.xjust.controller;

import com.xjust.utils.JwtUtils;
import com.xjust.pojo.Result;
import com.xjust.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private LoginService loginService;
    @PostMapping("/login")
    public Result login(@RequestBody Map<String,Object> emp){
        Map<String,Object> e = loginService.login(emp);
      if(e!=null){
          Map<String,Object> claims = new HashMap<>();
          claims.put("id",e.get("Id"));
          claims.put("username",e.get("username"));
         String token = JwtUtils.generateJwt(claims);
          return Result.success(token);
      }
       return Result.error("用户名或密码错误");
    }
    //注册
    @PostMapping("/register")
    public Result register(@RequestBody Map<String,Object> register){
        Map<String,Object> e = loginService.login(register);
        if(e!=null){
            return Result.error("用户名存在重复");
        }else{
            loginService.register(register);
            return Result.success();
        }
    }
}
